import {computed, ref} from "vue"
import type {SwitchProp} from "../type/SwitchProp.ts"
import type {SwitchEmit} from "@/components/switch/type/SwitchEmit.ts";
import {mixHexWithWhite} from "../../utils.ts"

/**
 * created by yangtong on 2025/6/14 下午5:22
 * <br/>
 * switch组件的逻辑代码
 */
export function useSwitch<T = boolean | string | number>($prop: SwitchProp<T>, $emit: SwitchEmit<T>) {
    //switch宽度
    const width = ref()
    //switch激活时的value
    const activeVal = computed<T>(() =>
        $prop.activeValue !== undefined ? $prop.activeValue : (true as unknown as T)
    )
    //switch失活时的value
    const inactiveVal = computed<T>(() =>
        $prop.inactiveValue !== undefined ? $prop.inactiveValue : (false as unknown as T)
    )
    //判断switch是否激活
    const isActive = computed(() => $prop.modelValue === activeVal.value && !$prop.disabled)

    //当激活状态改变时的回调函数
    const switchChange = () => {
        if ($prop.disabled) {
            return
        }
        const currentValue: T = isActive.value ? inactiveVal.value : activeVal.value
        $emit('update:modelValue', currentValue)
        $emit('switchChange', currentValue)
    }

    //根据switch的显示内容，自动计算switch宽度
    const autoWidth = () => {
        const maxLen = Math.max(
            $prop.inactiveText?.length || 0,
            $prop.activeText?.length || 0
        )
        width.value = Math.max(maxLen * ($prop.fontSize ?? 16) + $prop.thumbSize! + 16, $prop.width ?? 50)
    }

    const lightActiveColor: string = mixHexWithWhite($prop.activeColor!)
    const lightInactiveColor: string = mixHexWithWhite($prop.inactiveColor!)

    return {width, isActive, switchChange, autoWidth, lightActiveColor, lightInactiveColor}
}